#include "widget.h"
#include "ui_widget.h"
#include <QGraphicsDropShadowEffect>
#include<opencv2/highgui/highgui_c.h>
#include<qfile.h>
#include<qfiledialog.h>
#include<qmessagebox.h>
#include<qtextcodec.h>
#include <QMouseEvent>
#include <Operation.hpp>
#include <windows.h>

using namespace std;
QRect labelPos;

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setProperty("canMove",true);
    this->initUi();
    this->initMember();
}

Widget::~Widget()
{
    delete ui;
}

/**********************************************************初始化函数****************************************************************/

void Widget::initUi()
{
    //初始化窗口边框
    this->setAttribute(Qt::WA_TranslucentBackground, true);
    this->setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
    shadow->setOffset(0, 0);
    shadow->setColor(QColor("#444444"));
    shadow->setBlurRadius(16);
    ui->w_bg->setGraphicsEffect(shadow);
    ui->lay_bg->setMargin(12);

    //Logo
    QPixmap logo(":/icons/logo.png");
    ui->lab_logo->setPixmap(logo);

    //itemLogo
    QPixmap item1(":/icons/item_01.png");
    QPixmap item2(":/icons/item_02.png");
    ui->lab_item_01->setPixmap(item1);
    ui->lab_item_02->setPixmap(item2);
}

void Widget::initMember()
{
    this->myMbox = new MyMessageBox();
    connect(myMbox,SIGNAL(btnchicked(int)),this,SLOT(changeMboxReturn(int)));

    //最小化到托盘
    QIcon icon = QIcon(":/icons/logo.png");//设置最小图标
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(icon);
    trayIcon->setToolTip("Peach"); //提示文字
    //添加托盘列表项(还原与退出)
    returnNormal = new QAction(" Show", this);
    returnNormal->setFont(QFont("Arial", 9));
    returnNormal->setObjectName("returnNormal");
    returnNormal->setIcon(QIcon(":/icons/show.png"));
    quitAction = new QAction(" Quit", this);
    quitAction->setFont(QFont("Arial", 9));
    quitAction->setObjectName("quitAction");
    quitAction->setIcon(QIcon(":/icons/out.png"));
    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));           //绑定槽函数退出
    connect(returnNormal, SIGNAL(triggered()), this, SLOT(showNormal()));   //绑定槽函数还原界面

    //创建托盘菜单(必须先创建动作，后添加菜单项，还可以加入菜单项图标美化)
    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(returnNormal);
    trayIconMenu->addAction(quitAction);
    trayIcon->setContextMenu(trayIconMenu);
}

/**********************************************************自定义函数****************************************************************/

void Widget::littleShow()
{
    this->hide();//隐藏主窗口
    trayIcon->show();//显示托盘

    //显示到系统提示框的信息
    QString title="Peach";
    QString text="正自动在后台运行";
    trayIcon->showMessage(title,text,QSystemTrayIcon::Information,3000); //此参数为提示时长
}

/**********************************************************控件槽函数****************************************************************/

void Widget::closeEvent(QCloseEvent *event)
{
    myMbox->setIcon("question");
    myMbox->setBodyText("How to leave?");
    myMbox->setButtonText("Little","Logout");
    myMbox->exec();
    if(mbox_return == 0) {
        event->ignore();
    }else if(mbox_return == 1){
        event->ignore();
        littleShow();
    }
}

void Widget::Widget::changeMboxReturn(int num)
{
    this->mbox_return = num;
}

/********************************************选择图片************************************************/

void Widget::on_selectForeBtn_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), ".", tr("Image File (*.jpg *.png *.bmp)"));
    QTextCodec* code = QTextCodec::codecForName("gb18030");
    string name = code->fromUnicode(fileName).data();
    this->foregdImg = cv::imread(name);
    if (!this->foregdImg.data)
    {
        QMessageBox msgBox;
        msgBox.warning(this, "Warning", "Failed to open the image!");
    }
    else
    {
        cv::Mat rgb;
        QImage qimg;
        if (this->foregdImg.channels() == 3)
        {
            cvtColor(this->foregdImg, rgb, cv::COLOR_BGR2RGB);
            qimg = QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
        }
        else
        {
            qimg = QImage((const unsigned char*)(this->foregdImg.data), this->foregdImg.cols, this->foregdImg.rows, this->foregdImg.cols * this->foregdImg.channels(), QImage::Format_RGB888);
        }
        qimg = qimg.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);
        ui->imgLabel->setPixmap(QPixmap::fromImage(qimg));
        this->scaledForegdImg = cv::Mat(qimg.height(), qimg.width(), CV_8UC3, (void*)qimg.constBits(), qimg.bytesPerLine());
        foregdScale = double(this->scaledForegdImg.rows) / double(this->foregdImg.rows);
        cvtColor(this->scaledForegdImg, this->scaledForegdImg, cv::COLOR_BGR2RGB);
    }
}

void Widget::on_selectBackBtn_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), ".", tr("Image File (*.jpg *.png *.bmp)"));
    QTextCodec* code = QTextCodec::codecForName("gb18030");
    string name = code->fromUnicode(fileName).data();
    this->backgdImg = cv::imread(name);
    if (!this->backgdImg.data)
    {
        QMessageBox msgBox;
        msgBox.warning(this, "Warning", "Failed to open the image!");
    }
    else
    {
        cv::Mat rgb;
        QImage qimg;
        if (this->backgdImg.channels() == 3)
        {
            cvtColor(this->backgdImg, rgb, cv::COLOR_BGR2RGB);
            qimg = QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
        }
        else
        {
            qimg = QImage((const unsigned char*)(this->backgdImg.data), this->backgdImg.cols, this->backgdImg.rows, this->backgdImg.cols * this->backgdImg.channels(), QImage::Format_RGB888);
        }
        qimg = qimg.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);
        ui->imgLabel->setPixmap(QPixmap::fromImage(qimg));
        this->scaledBackgdImg = cv::Mat(qimg.height(), qimg.width(), CV_8UC3, (void*)qimg.constBits(), qimg.bytesPerLine());
        backgdScale = double(this->scaledBackgdImg.rows) / double(this->backgdImg.rows);
        cvtColor(this->scaledBackgdImg, this->scaledBackgdImg, cv::COLOR_BGR2RGB);
    }
}



/********************************************选择视图************************************************/

void Widget::on_foregdBtn_clicked()
{
    if (!this->foregdImg.data)
    {
        QMessageBox msgBox;
        msgBox.warning(this, "Warning", "Failed to open the image!");
    }
    else
    {
        cv::Mat rgb;
        QImage qimg;
        if (this->foregdImg.channels() == 3)
        {
            cvtColor(this->foregdImg, rgb, cv::COLOR_BGR2RGB);
            qimg = QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
        }
        else
        {
            qimg = QImage((const unsigned char*)(this->foregdImg.data), this->foregdImg.cols, this->foregdImg.rows, this->foregdImg.cols * this->foregdImg.channels(), QImage::Format_RGB888);
        }
        qimg = qimg.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);
        ui->imgLabel->setPixmap(QPixmap::fromImage(qimg));
        this->scaledForegdImg = cv::Mat(qimg.height(), qimg.width(), CV_8UC3, (void*)qimg.constBits(), qimg.bytesPerLine());
        foregdScale = double(this->scaledForegdImg.rows) / double(this->foregdImg.rows);
        cvtColor(this->scaledForegdImg, this->scaledForegdImg, cv::COLOR_BGR2RGB);
    }
}

void Widget::on_backgdBtn_clicked()
{
    if (!this->backgdImg.data)
    {
        QMessageBox msgBox;
        msgBox.warning(this, "Warning", "Failed to open the image!");
    }
    else
    {
        cv::Mat rgb;
        QImage qimg;
        if (this->backgdImg.channels() == 3)
        {
            cvtColor(this->backgdImg, rgb, cv::COLOR_BGR2RGB);
            qimg = QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
        }
        else
        {
            qimg = QImage((const unsigned char*)(this->backgdImg.data), this->backgdImg.cols, this->backgdImg.rows, this->backgdImg.cols * this->backgdImg.channels(), QImage::Format_RGB888);
        }
        qimg = qimg.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);
        ui->imgLabel->setPixmap(QPixmap::fromImage(qimg));
        this->scaledBackgdImg = cv::Mat(qimg.height(), qimg.width(), CV_8UC3, (void*)qimg.constBits(), qimg.bytesPerLine());
        backgdScale = double(this->scaledBackgdImg.rows) / double(this->backgdImg.rows);
        cvtColor(this->scaledBackgdImg, this->scaledBackgdImg, cv::COLOR_BGR2RGB);
    }
}

void Widget::on_maskBtn_clicked()
{
    if (!this->mask.data)
    {
        QMessageBox msgBox;
        msgBox.warning(this, "Warning", "Failed to open the image!");
    }
    else
    {
        cv::Mat rgb;
        QImage qimg;
        if (this->mask.channels() == 3)
        {
            cvtColor(this->mask, rgb, cv::COLOR_BGR2RGB);
            qimg = QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
        }
        else
        {
            qimg = QImage((const unsigned char*)(this->mask.data), this->mask.cols, this->mask.rows, this->mask.cols * this->mask.channels(), QImage::Format_Grayscale8);
        }
        qimg = qimg.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);
        ui->imgLabel->setPixmap(QPixmap::fromImage(qimg));
    }
}

void Widget::on_ResultBtn_clicked()
{
    if (!this->result.data)
    {
        QMessageBox msgBox;
        msgBox.warning(this, "Warning", "Failed to open the image!");
    }
    else
    {
        cv::Mat rgb;
        QImage qimg;
        if (this->result.channels() == 3)
        {
            cvtColor(this->result, rgb, cv::COLOR_BGR2RGB);
            qimg = QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
        }
        else
        {
            qimg = QImage((const unsigned char*)(this->result.data), this->result.cols, this->result.rows, this->result.cols * this->result.channels(), QImage::Format_RGB888);
        }
        qimg = qimg.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);
        ui->imgLabel->setPixmap(QPixmap::fromImage(qimg));
    }
}


/********************************************选择功能************************************************/

void Widget::on_saveImgBtn_clicked()
{
    if (!this->result.data)
    {
        QMessageBox msgBox;
        msgBox.warning(this, "Warning", "Dst data is Null!");
    }
    else
    {
        QString filePath = QFileDialog::getSaveFileName(this, tr("Save Image"), "", tr("Images (*.png *.bmp *.jpg)")); //选择路径
        if (filePath.isEmpty())
        {
            QMessageBox::information(this, "Informaton", "Failed to save dst!");
        }
        else
        {
            string savePath = filePath.toStdString();
            imwrite(savePath, this->result);
        }
    }
}

void Widget::on_cutBtn_clicked()
{
    this->on_foregdBtn_clicked();
    // 取得ui->label的中心位置以及缩放后图片的大小
    QPoint center = mapToGlobal(ui->imgLabel->pos());
    center = QPoint(center.x() + (ui->imgLabel->size().width()) / 2 + 285,
        center.y() + (ui->imgLabel->size().height()) / 2 + 72);
    QSize size = QSize(scaledForegdImg.cols, scaledForegdImg.rows);
    helper* helperWidget = new helper(center, size);
    connect(helperWidget, SIGNAL(signalCompleteCature(int, int, int, int)), this, SLOT(onCompleteCature(int, int, int, int)));
    helperWidget->show();
}

void Widget::onCompleteCature(int x, int y, int h, int w)
{
    cv::Mat bgModel, fgModel;
    // 输出结果，结果为：GC_BGD =0（背景）,GC_FGD =1（前景）,GC_PR_BGD = 2（可能的背景）, GC_PR_FGD = 3（可能的前景）
    
    // 取得ROI
    roi = cv::Rect(x, y , h , w );
    cv::Mat src;
    cv::resize(this->foregdImg, src, cv::Size(foregdImg.size().width * foregdScale, foregdImg.size().height * foregdScale));
    cv::Mat mask = cv::Mat::zeros(src.size(), CV_8UC1);
    
    grabcutter(src, mask, roi, bgModel, fgModel, 1, cv::GC_INIT_WITH_RECT);
    //比较result的值为可能的前景像素才输出到result中
    compare(mask, cv::GC_PR_FGD, mask, cv::CMP_EQ);
    
    if (!this->backgdImg.data)
    {
        cv::Mat back(src.size(), CV_8UC3, cv::Scalar(255, 255, 255));
        this->mask = mask;
        changeBackGD(src, back, mask, this->result, false);
    }
    else
    {
        this->mask = mask;
        changeBackGD(src, this->backgdImg, mask, this->result, true);
    }
}

void Widget::on_magicBtn_clicked()
{
    cv::Mat src;
    cv::Mat bgModel, fgModel;
    cv::resize(this->foregdImg, src, cv::Size(foregdImg.size().width * foregdScale, foregdImg.size().height * foregdScale));
    yolo.detect(src);
    cv::Mat mask = cv::Mat::zeros(src.size(), CV_8UC1);

    grabcutter(src, mask, yolo.getLargestBox(), bgModel, fgModel, 1, cv::GC_INIT_WITH_RECT);
    compare(mask, cv::GC_PR_FGD, mask, cv::CMP_EQ);

    cv::Mat detectSrc = yolo.getFrame();
    cv::Mat rgb;
    QImage qimg;
    cvtColor(detectSrc, rgb, cv::COLOR_BGR2RGB);
    qimg = QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
    qimg = qimg.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);
    ui->imgLabel->setPixmap(QPixmap::fromImage(qimg));

    if (!this->backgdImg.data)
    {
        cv::Mat back(src.size(), CV_8UC3, cv::Scalar(255, 255, 255));
        this->mask = mask;
        changeBackGD(src, back, mask, this->result, false);
    }
    else
    {
        this->mask = mask;
        changeBackGD(src, this->backgdImg, mask, this->result, true);
    }
}


void Widget::on_watershedBtn_clicked()
{

    cv::Mat src;
    labelsz = cv::Size(ui->imgLabel->size().width(), ui->imgLabel->size().height());

    labelPos = ui->imgLabel->geometry(); // 记录label左上角位置
    QPoint preCenter = QPoint(labelPos.x() + int(labelsz.width / 2), labelPos.y() + int(labelsz.height / 2)); // label中心点

    cv::resize(this->foregdImg, src, cv::Size(foregdImg.size().width * foregdScale, foregdImg.size().height * foregdScale));
    ui->imgLabel->setGeometry(labelPos.x(), labelPos.y(), src.cols, src.rows); //调整label大小

    QPoint nowCenter = QPoint(labelPos.x() + int(src.cols / 2), labelPos.y() + int(src.rows / 2)); // resize后label的中心
    QRect nowPos = QRect(labelPos.x() + preCenter.x() - nowCenter.x(), labelPos.y() + preCenter.y() - nowCenter.y(), src.cols, src.rows); // 偏移label
    ui->imgLabel->setGeometry(nowPos);

    ui->imgLabel->setPixmap(QPixmap("")); //清除原来的图片
    QImage qimg;
    cv::Mat rgb;
    if (src.channels() == 3)
    {
        cvtColor(src, rgb, cv::COLOR_BGR2RGB);
        qimg = QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
    }
    else
    {
        qimg = QImage((const unsigned char*)(src.data), src.cols, src.rows, src.cols * src.channels(), QImage::Format_RGB888);
    }
    qimg = qimg.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);
    ui->imgLabel->setAlignment(Qt::AlignLeft);
    ui->imgLabel->setPixmap(QPixmap::fromImage(qimg));

    //利用窗口句柄绑定窗口,引用WIN API，所有头文件中不能使用cv命名空间，因为winApi也有一个cv命名空间，会冲突
    cv::namedWindow("ps", cv::WINDOW_NORMAL);//创建窗口
    cv::resizeWindow("ps", cv::Size(src.cols, src.rows));
    HWND hwnd1 = (HWND)cvGetWindowHandle("ps");
    HWND hparent = GetParent(hwnd1);//获取父窗口
    SetParent(hwnd1, (HWND)ui->imgLabel->winId());//设置父窗口
    ShowWindow(hparent, SW_HIDE);//显示窗口，之前的设置为隐藏
    cv::imshow("ps", src);
    src.copyTo(wsgloimg);





    using namespace cv;
    Mat img, imgGray;
    Mat maskWaterShed;
    //img = imread("C:\\Users\\86199\\Desktop\\photo\\photo\\hg.png"); //原图
    //if (img.empty()) {
       // cout << "correct file name!" << endl;
        //return -1;
    //}
    img = src;
    cvtColor(img, imgGray, COLOR_BGR2GRAY);
    imgmask = Mat::zeros(img.size(), CV_8UC3);
    img.copyTo(imgmaskshow);
    //Canny(imgGray, imgmask, 150, 300);
    imshow("mask", imgmaskshow);
    imshow("ps", img);
    cv::setMouseCallback("ps", WaterShedMouse, 0);
    waitKey(0);
    cv::setMouseCallback("ps", NULL, NULL);
    cv::destroyWindow("ps");
    vector<vector<Point>>contours;
    vector<Vec4i>hierarchy;
    cvtColor(imgmask, imgmask, COLOR_BGR2GRAY);
    findContours(imgmask, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
    cout << contours.size();
    maskWaterShed = Mat::zeros(imgmask.size(), CV_32S);
    for (int index = 0; index < contours.size(); index++) {
        drawContours(maskWaterShed, contours, index, Scalar::all(index + 1), -1, 8, hierarchy, INT_MAX);


    }
    watershed(img, maskWaterShed);
    vector<Vec3b> colors;
    for (int i = 0; i < contours.size(); i++) {
        int b = theRNG().uniform(0, 255);
        int g = theRNG().uniform(0, 255);
        int r = theRNG().uniform(0, 255);
        colors.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r));

    }
    Mat resultImg = Mat(img.size(), CV_8UC3);
    for (int i = 0; i < imgmask.rows; i++) {
        for (int j = 0; j < imgmask.cols; j++) {

            int index = maskWaterShed.at<int>(i, j);
            if (index == -1) {
                resultImg.at<Vec3b>(i, j) = Vec3b(255, 255, 255);

            }
            else if (index <= 0 || index > contours.size()) {
                resultImg.at<Vec3b>(i, j) = Vec3b(0, 0, 0);
            }
            else
            {
                resultImg.at<Vec3b>(i, j) = colors[index - 1];


            }
        }

    }

    ///resultImg = resultImg * 1 ;
    resultImg = resultImg * 0.6 + img * 0.4;
    imshow("watershed_result", resultImg);
    for (int n = 1; n <= contours.size(); n++) {
        Mat resImage1 = Mat(img.size(), CV_8UC3);

        for (int i = 0; i < imgmask.rows; i++) {
            for (int j = 0; j < imgmask.cols; j++) {
                int index = maskWaterShed.at<int>(i, j);
                if (index == n) {
                    resImage1.at<Vec3b>(i, j) = img.at<Vec3b>(i, j);
                   
                }
                else
                    resImage1.at<Vec3b>(i, j) = Vec3b(0, 0, 0);
  
            }
        }
        
      
        if (n == 1) {
            Mat resImage2 = Mat(img.size(), CV_8UC1);

            for (int i = 0; i < imgmask.rows; i++) {
                for (int j = 0; j < imgmask.cols; j++) {
                    int index = maskWaterShed.at<int>(i, j);
                    if (index == n) {
                        resImage2.at<uchar>(i, j) = 255;

                    }
                    else
                        resImage2.at<uchar>(i, j) = 0;

                }
            }
         


            
            mask = resImage2;
            if (!this->backgdImg.data)
            {
                cv::Mat back(src.size(), CV_8UC3, cv::Scalar(255, 255, 255));
                this->mask = mask;
                changeBackGD(src, back, mask, this->result, false);
            }
            else
            {
                this->mask = mask;
                changeBackGD(src, this->backgdImg, mask, this->result, true);
            }
        }
        
        String name = "C:\\Users\\10184\\Desktop\\digital\\ROI"+ to_string(n)+".png";
        vector<int> compression_params;
        compression_params.push_back(IMWRITE_PNG_COMPRESSION);
        compression_params.push_back(9);
        cv::imwrite(name, resImage1, compression_params);

        //imshow(to_string(n), resImage1);
    }

    //waitKey(0);
    //return 0;


   // cv::setMouseCallback("ps", WaterShedMouse, 0);
}

void Widget::on_watershedCutBtn_clicked()
{

}

void Widget::on_lassoBtn_clicked()
{

    LWPath.clear();
    cv::Mat src;
    labelsz = cv::Size(ui->imgLabel->size().width(), ui->imgLabel->size().height());

    labelPos = ui->imgLabel->geometry(); // 记录label左上角位置
    QPoint preCenter = QPoint(labelPos.x() + int(labelsz.width / 2), labelPos.y() + int(labelsz.height / 2)); // label中心点

    cv::resize(this->foregdImg, src, cv::Size(foregdImg.size().width * foregdScale, foregdImg.size().height * foregdScale));
    ui->imgLabel->setGeometry(labelPos.x(), labelPos.y(), src.cols, src.rows); //调整label大小

    QPoint nowCenter = QPoint(labelPos.x() + int(src.cols / 2), labelPos.y() + int(src.rows / 2)); // resize后label的中心
    QRect nowPos = QRect(labelPos.x() + preCenter.x() - nowCenter.x(), labelPos.y() + preCenter.y() - nowCenter.y(), src.cols, src.rows); // 偏移label
    ui->imgLabel->setGeometry(nowPos);

    ui->imgLabel->setPixmap(QPixmap("")); //清除原来的图片
    QImage qimg;
    cv::Mat rgb;
    if (src.channels() == 3)
    {
        cvtColor(src, rgb, cv::COLOR_BGR2RGB);
        qimg = QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
    }
    else
    {
        qimg = QImage((const unsigned char*)(src.data), src.cols, src.rows, src.cols * src.channels(), QImage::Format_RGB888);
    }
    qimg = qimg.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);
    ui->imgLabel->setAlignment(Qt::AlignLeft);
    ui->imgLabel->setPixmap(QPixmap::fromImage(qimg));

    //利用窗口句柄绑定窗口,引用WIN API，所有头文件中不能使用cv命名空间，因为winApi也有一个cv命名空间，会冲突
    cv::namedWindow("ps", cv::WINDOW_NORMAL);//创建窗口
    cv::resizeWindow("ps", cv::Size(src.cols, src.rows));
    HWND hwnd1 = (HWND)cvGetWindowHandle("ps");
    HWND hparent = GetParent(hwnd1);//获取父窗口
    SetParent(hwnd1, (HWND)ui->imgLabel->winId());//设置父窗口
    ShowWindow(hparent, SW_HIDE);//显示窗口，之前的设置为隐藏
    cv::imshow("ps", src);
    src.copyTo(glbImg);
    lw.loadImage(glbImg);
    cv::setMouseCallback("ps", LWMouse, 0);
}

void Widget::on_lassoCutBtn_clicked()
{
    cv::Mat src, dst;
    cv::resize(this->foregdImg, src, cv::Size(foregdImg.size().width * foregdScale, foregdImg.size().height * foregdScale));
    CreateLWMask(src, LWPath, this->mask);

    src.copyTo(dst);
    for (int ii = 1; ii < LWPath.size(); ii++)
    {
        cv::line(dst, LWPath[ii - 1], LWPath[ii], cv::Scalar(0, 0, 255), 2);
    }
    cv::Mat rgb;
    QImage qimg;
    if (dst.channels() == 3)
    {
        cvtColor(dst, rgb, cv::COLOR_BGR2RGB);
        qimg = QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
    }
    qimg = qimg.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);
    ui->imgLabel->setPixmap(QPixmap::fromImage(qimg));

    if (!this->backgdImg.data)
    {
        cv::Mat back(src.size(), CV_8UC3, cv::Scalar(255, 255, 255));
        this->mask = mask;
        changeBackGD(src, back, mask, this->result, false);
    }
    else
    {
        this->mask = mask;
        changeBackGD(src, this->backgdImg, mask, this->result, true);
    }
}

void Widget::on_resetBtn_clicked()
{
    ui->imgLabel->setGeometry(labelPos);
    ui->imgLabel->resize(labelsz.width, labelsz.height);
    ui->imgLabel->setAlignment(Qt::AlignCenter);
}

void Widget::on_changeBtn_clicked()
{
    if (this->foregdImg.data && this->mask.data)
    {
        cv::Mat src;
        cv::resize(this->foregdImg, src, cv::Size(foregdImg.size().width * foregdScale, foregdImg.size().height * foregdScale));
        if (!this->backgdImg.data)
        {
            cv::Mat back(src.size(), CV_8UC3, cv::Scalar(255, 255, 255));
            this->mask = mask;
            changeBackGD(src, back, mask, this->result, false);
        }
        else
        {
            this->mask = mask;
            changeBackGD(src, this->backgdImg, mask, this->result, true);
        }
        this->on_ResultBtn_clicked();
    }
    else
    {
        QMessageBox msgBox;
        msgBox.warning(this, "Warning", "Failed to change backgound! please check your operation!");
    }
}



/********************************************窗口事件************************************************/

void Widget::on_btn_logout_clicked()
{
    close();
}

void Widget::on_btn_littleshow_clicked()
{
    showMinimized();
}
